// 添加新的状态变量来存储表格数据
var tableData = [];

// 分页配置
var pageConfig = {
	currentPage: 1,
	pageSize: 10,
	total: 0,  // 初始化为0
}

var modalPagination = null;
var isTranslationSearchHandlersInitialized = false;

// 存储当前翻译模态框的状态
var currentTranslationState = {
	pageId: null,
	originalLang: null,
	translatedLang: null
};

// 添加获取数据的函数
function fetchTableData(shouldInitPagination) {
	shouldInitPagination = shouldInitPagination !== false; // 默认为true
	
	var params = {
		page: pageConfig.currentPage,
		page_size: pageConfig.pageSize,
		keyword: '',
		language: ''
	};

	// 安全地获取输入值
	var keywordInput = document.querySelector('.search-input:first-child input');
	var languageInput = document.querySelector('.search-input:last-child input');
	if (keywordInput) params.keyword = keywordInput.value || '';
	if (languageInput) params.language = languageInput.value || '';

	admin_app.getCacheList(
		params,
		function(data) {
			tableData = data.list || [];
			pageConfig.total = data.total || tableData.length;
			pageConfig.currentPage = data.page || 1;
			pageConfig.pageSize = data.page_size || 10;
			
			renderTable();
			if (shouldInitPagination) {
				initializePagination();
			}
		},
		function(error) {
			console.error('获取数据失败:', error);
		}
	);
}

// 初始化表格和分页
function initializeCache() {
	fetchTableData();
	setupSearchHandlers();
}

// 渲染表格数据
function renderTable(filteredData) {
	filteredData = filteredData || tableData;
	var tbody = document.querySelector('.table-container tbody');
	
	var html = '';
	for (var i = 0; i < filteredData.length; i++) {
		var item = filteredData[i];
		// 计算序号：(当前页码-1) * 每页数量 + 当前索引 + 1
		var serialNumber = (pageConfig.currentPage - 1) * pageConfig.pageSize + i + 1;
		
		// 确保 id 和 page_id 存在且为数字
		var id = parseInt(item.id, 10);
		var pageId = parseInt(item.page_id, 10);
		
		if (isNaN(id) || isNaN(pageId)) {
			console.error('Invalid id or page_id:', item);
			continue;
		}

		var flagsHtml = '';
		for (var j = 0; j < item.lang.length; j++) {
			var flag = item.lang[j];
			flagsHtml += '<img src="' + assetsUri + '/images/flags/' + flag.code + '.svg" alt="' + flag.code + ' flag" data-value="' + flag.name + '">';
		}
		
		html += '<tr class="table-row" data-id="' + id + '">' +
			'<td>' + serialNumber + '</td>' +
			'<td>' + item.url + '</td>' +
			'<td><div class="flag-list" data-id="' + id + '">' + flagsHtml + '</div></td>' +
			'<td>' + item.created_at + '</td>' +
			'<td><div class="action-list" data-id="' + id + '" data-page_id="' + pageId + '">' +
			'<img src="' + assetsUri + '/images/page/' + (item.is_locked === 1 ? 'unlock' : 'locked') + '.svg" ' +
			'alt="' + (item.is_locked === 1 ? 'unlock' : 'locked') + '"></div></td>' +
			'</tr>';
	}
	
	tbody.innerHTML = html;

	// flag icon click event
	// var flagLists = tbody.querySelectorAll('.flag-list');
	// for (var k = 0; k < flagLists.length; k++) {
	// 	(function(row) {
	// 		row.addEventListener('click', function(event) {
	// 			var id = parseInt(row.dataset.id, 10);
	// 			if (isNaN(id)) return;
				
	// 			var item = null;
	// 			for (var l = 0; l < filteredData.length; l++) {
	// 				if (parseInt(filteredData[l].id, 10) === id) {
	// 					item = filteredData[l];
	// 					break;
	// 				}
	// 			}
				
	// 			var target = event.target;
	// 			var lang = target.alt ? target.alt.split(' ')[0] : null;
	// 			var langName = target.dataset.value;
	// 			if (langName && item) {
	// 				showTranslationModal(item, lang, langName);
	// 			}
	// 		});
	// 	})(flagLists[k]);
	// }

	// action icon click event
	var actionLists = tbody.querySelectorAll('.action-list');
	for (var m = 0; m < actionLists.length; m++) {
		(function(row) {
			row.addEventListener('click', function(event) {
				var pageId = parseInt(row.dataset.page_id, 10);
				var cacheId = parseInt(row.dataset.id, 10);
				
				if (isNaN(pageId) || isNaN(cacheId)) {
					console.error('Invalid page_id or cache_id:', row.dataset);
					fc5_utils.showTip('Invalid page or cache ID');
					return;
				}
				
				var isLocked = event.target.src.indexOf('unlock.svg') !== -1;
				showConfirmModal(cacheId, pageId, row, isLocked);
			});
		})(actionLists[m]);
	}
}

// 初始化分页器
function initializePagination() {
	var totalPages = Math.ceil(pageConfig.total / pageConfig.pageSize);
	var pageNumbers = document.querySelector('.page-numbers');
	var prevBtn = document.querySelector('.prev-btn');
	var nextBtn = document.querySelector('.next-btn');
	var gotoInput = document.querySelector('.goto-input');

	// 更新页码显示
	function updatePageNumbers() {
		var pages = [];
		if (totalPages <= 7) {
			for (var i = 1; i <= totalPages; i++) {
				pages.push(i);
			}
		} else {
			if (pageConfig.currentPage <= 3) {
				pages = [1, 2, 3, 4, 5, '...', totalPages];
			} else if (pageConfig.currentPage >= totalPages - 2) {
				pages = [1, '...', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
			} else {
				pages = [1, '...', pageConfig.currentPage - 1, pageConfig.currentPage, pageConfig.currentPage + 1, '...', totalPages];
			}
		}

		var html = '';
		for (var i = 0; i < pages.length; i++) {
			var page = pages[i];
			if (page === '...') {
				html += '<span class="ellipsis">...</span>';
			} else {
				html += '<span class="page-number ' + (page === pageConfig.currentPage ? 'active' : '') + '">' + page + '</span>';
			}
		}
		pageNumbers.innerHTML = html;
	}

	// 更新按钮状态
	function updateButtons() {
		prevBtn.disabled = pageConfig.currentPage === 1;
		nextBtn.disabled = pageConfig.currentPage === totalPages;
		gotoInput.value = pageConfig.currentPage;
	}

	// 切换页面
	function changePage(page) {
		if (page >= 1 && page <= totalPages) {
			pageConfig.currentPage = page;
			fetchTableData(false);
			updatePageNumbers();
			updateButtons();
		}
	}

	// 绑定事件
	prevBtn.addEventListener('click', function() {
		changePage(pageConfig.currentPage - 1);
	});
	
	nextBtn.addEventListener('click', function() {
		changePage(pageConfig.currentPage + 1);
	});

	pageNumbers.addEventListener('click', function(e) {
		var pageNumber = e.target.closest('.page-number');
		if (pageNumber && !pageNumber.classList.contains('active')) {
			changePage(parseInt(pageNumber.textContent, 10));
		}
	});

	gotoInput.addEventListener('keypress', function(e) {
		if (e.key === 'Enter') {
			var page = parseInt(e.target.value, 10);
			if (page >= 1 && page <= totalPages) {
				changePage(page);
			} else {
				e.target.value = pageConfig.currentPage;
			}
		}
	});

	// 初始化显示
	updatePageNumbers();
	updateButtons();
}

// 设置搜索功能
function setupSearchHandlers() {
	var keywordSearchIcon = document.querySelector('.search-input:first-child .search-icon');
	var languageSearchIcon = document.querySelector('.search-input:last-child .search-icon');
	var searchTimeout;

	function handleSearch() {
		if (searchTimeout) {
			clearTimeout(searchTimeout);
		}
		searchTimeout = setTimeout(function() {
			fetchTableData();
		}, 300);
	}

	if (keywordSearchIcon) {
		keywordSearchIcon.addEventListener('click', handleSearch);
	}
	if (languageSearchIcon) {
		languageSearchIcon.addEventListener('click', handleSearch);
	}
}

// 渲染翻译列表
function renderTranslations(page) {
	page = page || 1;
	if (!currentTranslationState.pageId) return;
	
	var tbody = document.querySelector('.translation-modal .translation-list tbody');
	var keywordInput = document.querySelector('.search-box:first-child input');
	
	var params = {
		page_id: currentTranslationState.pageId,
		original_lang: currentTranslationState.originalLang,
		translated_lang: currentTranslationState.translatedLang,
		keyword: keywordInput ? keywordInput.value : '',
		page: page,
		page_size: 10
	};

	admin_app.getTranslationList(
		params,
		function(data) {
			var translations = data.list || [];
			var html = '';
			
			for (var i = 0; i < translations.length; i++) {
				var trans = translations[i];
				html += '<tr><td>' + trans.original + '</td><td>' + trans.translated + '</td></tr>';
			}
			
			tbody.innerHTML = html;

			// 更新分页器
			if (!modalPagination) {
				modalPagination = new Pagination({
					container: document.querySelector('.translation-modal .modal-pagination'),
					total: data.total || 0,
					currentPage: data.page || 1,
					pageSize: 10,
					onChange: renderTranslations
				});
			} else {
				modalPagination.update({
					total: data.total || 0,
					currentPage: data.page
				});
			}
		},
		function(error) {
			console.error('获取翻译数据失败:', error);
			tbody.innerHTML = '<tr><td colspan="2">获取数据失败</td></tr>';
		}
	);
}

// 设置翻译模态框的搜索处理程序
function setupTranslationModalSearchHandlers() {
	if (isTranslationSearchHandlersInitialized) {
		return;
	}
	
	var keywordInput = document.querySelector('.search-box:first-child input');
	var searchIcon = document.querySelector('.search-box:first-child .search-icon');
	var searchTimeout;

	function handleSearch() {
		if (searchTimeout) {
			clearTimeout(searchTimeout);
		}
		searchTimeout = setTimeout(function() {
			renderTranslations(1);
		}, 300);
	}

	if (searchIcon) {
		searchIcon.addEventListener('click', handleSearch);
	}
	isTranslationSearchHandlersInitialized = true;
}

// 显示翻译详情弹窗
function showTranslationModal(item, lang, langName) {
	// 更新当前翻译状态
	currentTranslationState = {
		pageId: item.page_id,
		originalLang: item.original_lang,
		translatedLang: lang
	};

	// 创建遮罩层
	var overlay = document.createElement('div');
	overlay.className = 'modal-overlay';
	document.body.appendChild(overlay);

	// 显示弹窗
	var modal = document.querySelector('.translation-modal');
	modal.style.display = 'block';

	// 更新弹窗标题
	var title = modal.querySelector('.modal-title');
	title.innerHTML = '<span>' + item.original_lang_name + '</span> > <span>' + langName + '</span>';

	// 绑定关闭事件
	var closeBtn = modal.querySelector('.close-btn');
	function closeModal() {
		modal.style.display = 'none';
		modal.classList.remove('magnify-modal');
		overlay.remove();
		// 清除当前翻译状态
		currentTranslationState = {
			pageId: null,
			originalLang: null,
			translatedLang: null
		};
	}

	closeBtn.addEventListener('click', closeModal);
	overlay.addEventListener('click', closeModal);

	// 初始渲染第一页
	renderTranslations(1);
	
	// 确保搜索处理程序只初始化一次
	setupTranslationModalSearchHandlers();
}

// 显示确认弹窗
function showConfirmModal(cacheId, pageId, row, isLocked) {
	var overlay = document.createElement('div');
	overlay.className = 'modal-overlay';
	document.body.appendChild(overlay);

	var modal = document.createElement('div');
	modal.className = 'confirm-modal';
	modal.innerHTML = 
		'<div class="modal-header">' +
			'<div class="modal-title">' + (isLocked ? 'unlock' : 'lock') + ' page</div>' +
			'<div class="modal-actions">' +
				'<div class="close-btn">' +
					'<img src="' + assetsUri + '/images/page/close.svg" alt="close">' +
				'</div>' +
			'</div>' +
		'</div>' +
		'<div class="modal-content">' +
			'<div class="modal-content-top">' +
				'<p>' +
					'<img src="' + assetsUri + '/images/page/warn.svg" alt="warning" class="warn-icon">' +
					'<span>Are you sure you want to ' + (isLocked ? 'unlock' : 'lock') + ' this page?</span>' +
				'</p>' +
			'</div>' +
			'<div class="modal-footer">' +
				'<button class="confirm-btn">confirm</button>' +
				'<button class="cancel-btn">cancel</button>' +
			'</div>' +
		'</div>';

	document.querySelector('.cache-container').appendChild(modal);

	// 绑定关闭事件
	modal.querySelector('.close-btn').addEventListener('click', closeModal);
	overlay.addEventListener('click', closeModal);

	// 绑定确认和取消事件
	modal.querySelector('.confirm-btn').addEventListener('click', function() {
		if (isLocked) {
			unlockPage(cacheId, pageId, row);
		} else {
			lockPage(cacheId, pageId, row);
		}
		closeModal();
	});
	
	modal.querySelector('.cancel-btn').addEventListener('click', closeModal);
}

// 关闭弹窗
function closeModal() {
	var overlay = document.querySelector('.modal-overlay');
	var modal = document.querySelector('.confirm-modal');
	if (overlay) overlay.remove();
	if (modal) modal.remove();
}

// 锁定页面
function lockPage(cacheId, pageId, row) {
	var intCacheId = parseInt(cacheId, 10);
	var intPageId = parseInt(pageId, 10);

	if (isNaN(intPageId) || isNaN(intCacheId)) {
		fc5_utils.showTip('Invalid page or cache ID');
		return;
	}

	var params = {
		cacheId: intCacheId,
		pageId: intPageId
	};

	admin_app.lockPage(
		params,
		function(data) {
			console.log('Lock page success:', data);
			var img = row.querySelector('img');
			img.src = assetsUri + '/images/page/unlock.svg';
			img.alt = 'unlock';
			fc5_utils.showTip('locked successfully');
		},
		function(error) {
			console.error('lock page failed:', error);
		}
	);
}

// 解锁页面
function unlockPage(cacheId, pageId, row) {
	var intCacheId = parseInt(cacheId, 10);
	var intPageId = parseInt(pageId, 10);

	if (isNaN(intPageId) || isNaN(intCacheId)) {
		fc5_utils.showTip('Invalid page or cache ID');
		return;
	}

	var params = {
		cacheId: intCacheId,
		pageId: intPageId
	};

	admin_app.unlockPage(
		params,
		function(data) {
			console.log('Unlock page success:', data);
			var img = row.querySelector('img');
			img.src = assetsUri + '/images/page/locked.svg';
			img.alt = 'locked';
			fc5_utils.showTip('unlocked successfully');
		},
		function(error) {
			console.error('unlock page failed:', error);
		}
	);
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
	initializeCache();
});

